package com.tang.plugin.utils;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.actionSystem.impl.ActionButton;
import com.intellij.openapi.actionSystem.impl.PresentationFactory;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.util.List;

public class ActionToolbarUtils {

    public static JComponent create(String place, List<Action> actions) {
        JPanel panel = new JPanel();

        panel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
        PresentationFactory factory = new PresentationFactory();
        actions.forEach(action -> {
            Presentation presentation = factory.getPresentation(action);
            presentation.setIcon(action.getIcon());
            presentation.setEnabled(action.isEnabled());
            presentation.setDescription(action.getDesc());

            ActionButton ab = new ActionButton(action, presentation, place, new Dimension(22, 24));
            ab.setIconInsets(JBUI.insets(0));
            panel.add(ab);
        });

        return panel;
    }

    public static class Action extends AnAction {

        private Icon icon;
        private boolean isEnabled;
        private String desc;
        private Callback callback;

        public Action(Icon icon, Callback callback) {
            this(icon, true, "", callback);
        }

        public Action(Icon icon, boolean isEnabled, String desc, Callback callback) {
            this.icon = icon;
            this.isEnabled = isEnabled;
            this.desc = desc;
            this.callback = callback;
        }

        @Override
        public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
            if (callback != null) {
                callback.invoke();
            }
        }

        public Icon getIcon() {
            return icon;
        }

        public boolean isEnabled() {
            return isEnabled;
        }

        public String getDesc() {
            return desc;
        }
    }


    public interface Callback {
        void invoke();
    }

}
